package com.example.mvvmdemo.ui.aty;

import com.example.mvvmdemo.ui.viewmodel.ViewModel;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import javax.inject.Inject;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public class BaseActivity<VM extends ViewModel> extends AppCompatActivity {

    @Inject
    VM viewModel;

    protected CompositeDisposable compositeDisposable;

    protected VM getViewModel() {
        return viewModel;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        compositeDisposable = new CompositeDisposable();
        bindBaseViewModel(getViewModel());
    }

    protected void addSubscriber(Disposable useCaseSubscriber) {
        compositeDisposable.add(useCaseSubscriber);
    }

    @SuppressLint("CheckResult")
    public void bindBaseViewModel(ViewModel viewModel) {
        if (viewModel!=null){
            addSubscriber( viewModel.getToastSubject()
                .subscribe(toastVm -> Toast.makeText(this, toastVm.getMsg(), Toast.LENGTH_SHORT).show()));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        compositeDisposable.clear();
        compositeDisposable.dispose();
        viewModel.destory();
    }
}
